<?php

namespace app\admin\model\facrm\product;

use think\Model;
use traits\model\SoftDelete;
class Type extends Model {

    use SoftDelete;

    // 表名
    protected $name = 'facrm_product_type';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';
    // 追加属性
    protected $append = [
    ];
    protected static function init()
    {
        self::afterInsert(function ($row) {
            if (!isset($row['weigh'])||!$row['weigh']){
                //创建时自动添加权重值
                $pk = $row->getPk();
                $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
            }

        });
    }
    public function object_array($array) {
        if (is_object($array)) {
            $array = (array) $array;
        } if (is_array($array)) {
            foreach ($array as $key => $value) {
                $array[$key] = $this->object_array($value);
            }
        }
        return $array;
    }

    /**
     * 根据名称获取分类ID
     * @param $name 分类名称
     * @param bool $is_insert 如果不存在是否插入
     * @return int 返回的分类ID
     */
    public static function getIdByName($name,$is_insert=false){
        static $typeids = [];
        if (isset($typeids[$name])) {
            return $typeids[$name];
        }
        $typeid=self::where('name',$name)->value('id');
        if ($typeid){
            $typeids[$name] = $typeid;
        }elseif (!$typeid&&$is_insert){
            //插入分类
            $selfModel= new self();
            $selfModel->save([
                'name'=>$name,
                'create_time'=>time(),
                'update_time'=>time(),
            ]);
            $typeid=$selfModel->getLastInsID();
            $typeid?$typeids[$name] = $typeid:'';
        }
        return $typeid;
    }
}
